package com.csxy.six.controller;

import com.csxy.six.R;
import com.csxy.six.entity.Goods;
import com.csxy.six.service.GoodsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "goods", description = "商品管理")
@RestController
@RequestMapping("/market/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Operation(summary = "根据id查询商品", description = "根据id查询商品")
    @GetMapping("/getById/{id}")
    public R getGoodsById(@PathVariable Integer id) {
        Goods goods = goodsService.getById(id);
        return R.ok().data("item", goods);
    }

    @Operation(summary = "查询所有商品", description = "查询所有商品")
    @GetMapping("/findAll")
    public R getAllGoods() {
        List<Goods> list = goodsService.list();
        return R.ok().data("items", list);
    }

    @Operation(summary = "新增商品", description = "新增商品")
    @PostMapping("/save")
    public R addGoods(@RequestBody Goods goods) {
        boolean flag = goodsService.getBaseMapper().insert(goods) > 0;
        if (flag) {
            return R.ok();
        }
        return R.error();
    }


    @Operation(summary = "修改商品", description = "修改商品")
    @PostMapping("/update")
    public R updateGoods(@RequestBody Goods goods) {
        boolean flag = goodsService.updateById(goods);
        if (flag) {
            return R.ok();
        }
        return R.error();
    }

    @Operation(summary = "删除商品", description = "根据id删除商品")
    @DeleteMapping("/remove/{id}")
    public R deleteGoodsById(@PathVariable Integer id) {
        boolean result = goodsService.removeById(id);
        if (result) {
            return R.ok();
        }
        return R.error();
    }

    @Operation(summary = "搜索商品", description = "根据关键字搜索商品")
    @GetMapping("/search")
    public R searchGoods(@RequestParam String keyword) {
        List<Goods> list = goodsService.searchGoods(keyword);
        return R.ok().data("items", list);
    }

    @Operation(summary = "增加商品浏览量", description = "增加商品浏览量")
    @PostMapping("/updateViewCount/{id}")
    public R incrementViewCount(@PathVariable Integer id) {
        boolean result = goodsService.incrementViewCount(id);
        if (result) {
            return R.ok();
        }
        return R.error();
    }
}
